package com.htpay.util;

import lombok.extern.slf4j.Slf4j;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
import java.util.*;

/**
 * 惠通客户端、签名校验等相关的工具类
 */
@Slf4j
public class HTPayClientUtil {
    public static String HTTP_URL = "http://microchat.15zxm.cn:3001/openApi/api/charge";


    /**
     * 发送工具类
     *
     * @param url
     * @return
     */
    public static String get(String url) {
        String result = "";
        try {
            URL getUrl = new URL(url);
            HttpURLConnection urlConnection = (HttpURLConnection) getUrl.openConnection();
            BufferedReader in = new BufferedReader(
                    new InputStreamReader(
                            urlConnection.getInputStream()));

            result = in.readLine().toString();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return result;
    }

    /**
     * 根据私密钥匙加密
     *
     * @param parameters
     * @param merchantKey
     * @return
     * @throws Exception
     */
    public static String createSign(Map<String, Object> parameters, String merchantKey) {
        log.info(parameters.keySet().toString());
        StringBuffer sbKey = new StringBuffer();
        List<String> keyList = new ArrayList<>(parameters.keySet());
        // 所有参与传参的参数按照accsii排序（升序）
        Collections.sort(keyList);
        for (int i = 0; i < keyList.size(); i++) {
            String k = keyList.get(i);
            Object v = parameters.get(k);
            //空值不传递，不参与签名组串
            if (null != v && !"".equals(v)) {
                sbKey.append(k + "=" + v + "&");
            }
        }
        sbKey.append("key=" + merchantKey);
        log.info("==== 携带私钥字符串:" + sbKey.toString() + " ====");
        //MD5加密,结果转换为大写字符
        String sign = MD5Util.MD5Encode(sbKey.toString(), "utf-8").toUpperCase();
        log.info("==== 根据接口访问数据获取sign[" + sign + "] ====");
        return sign;
    }

    public static void main(String[] args) throws UnsupportedEncodingException {
        Map<String, Object> params = new HashMap<String, Object>();

        params.put("merchantId", "1008");
        params.put("notifyUrl", "http%3A%2F%2Ftest.example.com");
        params.put("channelType", "101");
        params.put("totalMoney", "100");
        params.put("outTradeNo", "20191225153950123456");

        //JjHsAjBy090307040d0a02082v1G7Oe9
        createSign(params, "iJAio3VV090307040d0a0208nknHuh29");
    }
}
